<?php

namespace App\Admin\Controllers;

use App\Library\Logic\OperateLogLogic;
use App\Library\Logic\ProductSpecLogic;
use App\Library\Logic\ShopCategoryLogic;
use App\Library\Logic\ShopProductSpecsLogic;
use App\Library\Logic\ShopUserLogic;
use App\Library\Logic\ShopUserPriceLogic;
use App\Library\Logic\UserDmLogic;
use App\Library\Requests\Base\ActionRequest;
use App\Library\Requests\Base\BatchRequest;
use App\Library\Requests\Base\IdRequest;
use App\Models\AdminUsersModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class AjaxController extends AdminController
{
    /**
     * category
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function category(): array
    {
        $q = (int)request()->get('q');
        return DB::table('shop_category')
            ->where('category_status', 1)
            ->where('category_parent_id', $q)
            ->orderByDesc('sort')
            ->get(['category_id as id', 'category_name as text'])->toArray();
    }

    /**
     * cate
     * @param int $id
     * @return string
     */
    public function cate(int $id): string
    {
        $list = DB::table('shop_category')->where('category_status', 1)->where('category_parent_id', $id)
            ->get(['category_id', 'category_name']);
        $str = '<option></option>';
        foreach ($list as $v) $str .= "<option value='$v->category_id'>$v->category_name</option>";
        return $str;
    }

    public function getSpecByProductId(): Collection
    {
        return ProductSpecLogic::getByWhere(['productId' => request()->input('productId')]);
    }

    /**
     * @throws GuzzleException
     */
    public function webman(): string
    {
        $client = new Client;
        $response = $client->post('http://' . config('app.ip') . ':8054/api/' . request()->header('route'), [
            'json' => request()->input(),
            'verify' => false,
            'headers' => [
                'signature' => signature(),
                'newAuth' => request()->header('newAuth'),
            ],
        ]);
        return $response->getBody()->getContents();
    }

    /**
     * @throws GuzzleException
     */
    public function addImgOne(): string
    {
        $client = new Client;
        $fileName = 'img_file';
        $file = request()->file($fileName);
        $response = $client->post('http://' . config('app.ip') . ':8054/api/' . request()->header('route'), [
            'verify' => false,
            'headers' => [
                'signature' => signature(),
                'newAuth' => request()->header('newAuth'),
            ],
            'multipart' => [
                [
                    'name' => 'img_source_type',
                    'contents' => request()->input('img_source_type'),
                ],
                [
                    'name' => $fileName,
                    'filename' => $file->getClientOriginalName(),
                    'contents' => fopen($file->getRealPath(), 'r'),
                    'headers' => ['Content-Type' => $file->getMimeType()],
                ]
            ],
        ]);
        return $response->getBody()->getContents();
    }

    /**
     * addStaff
     * @return JsonResponse
     * @throws Exception
     */
    public function addStaff(): JsonResponse
    {
        $mobile = trim(request()->post('mobile'));
        if (empty($mobile)) return failMessage('手机号码格式错误');
        else if (!preg_match(__('com.mobileReg'), $mobile)) return failMessage('手机号码格式错误');
        $userId = Admin::user()->user_id;
        $currentShopUser = ShopUserLogic::detail($userId);
        if ($currentShopUser->user_main_id > 0) return failMessage('子账号,不能绑定员工帐号');
        $shopUser = ShopUserLogic::findByWhere(['userMobile' => $mobile, 'userDeleteFlag' => 2], null, ['userId', 'userMainId']);
        if (!is_null($shopUser)) {
            if ($shopUser->user_main_id > 0) {
                return failMessage("此帐号已经绑定到用户ID：{$shopUser->user_main_id}，不能重复绑定");
            }
            $shopUser->user_main_id = $userId;
            $shopUser->user_type = 3;//变更为员工
            $shopUser->user_peer_power = 1;
            $shopUser->user_applet_order = 1;
            $shopUser->save();
        } else {
            $secret = random();
            $password = random(16);
            $shopUser = ShopUserLogic::insertForModel([
                'userType' => 3,
                'userMainId' => $userId,
                'userNickname' => random(),
                'userName' => $mobile,
                'userMobile' => $mobile,
                'userSecret' => $secret,
                'userAppletOrder'=>1,
                'userPeerPower'=>1,
                'userPassword' => md5($password . $secret),
            ]);
            UserDmLogic::insertForModel('userId', $shopUser->user_id);
            ShopUserPriceLogic::add($shopUser->user_id);
        }
        mq('cacheUser', (string)$shopUser->user_id);
        OperateLogLogic::add(Admin::user()->user_id);
        if (!AdminUsersModel::query()->where(['user_id' => $shopUser->user_id])->exists()) {
            $adminModel = AdminUsersModel::insertForModel([
                'user_id' => $shopUser->user_id,
                'user_main_id' => $shopUser->user_main_id ?? 0,
                'username' => $mobile,
                'password' => Hash::make('666666'),
                'name' => $mobile,
                'admin_type'=>1
            ]);
            DB::table('admin_role_users')->insert([
                'role_id' => 3,
                'user_id' => $adminModel->id
            ]);
        }
        return success();
    }

    public function addCategory()
    {
        $categoryName = trim(request()->post('category_name'));
        if (empty($categoryName)) return failMessage('分类名不能为空');
        if (!is_null(ShopCategoryLogic::query()->where(['category_name' => $categoryName, 'category_parent_id' => 0, 'status_delete' => 0])->first())) return failMessage('名称不能重复');
        if (request()->post('sort') < 0) return failMessage('排序值不能为负数');
        ShopCategoryLogic::insertForModel([
            'categoryStatus' => is_null(request()->post('category_status')) ? 2 : request()->post('category_status'),
            'categoryName' => request()->post('category_name'),
            'sort' => is_null(request()->post('sort')) ? 0 : request()->post('sort'),
            'classImgUrl' => is_null(request()->post('category_img')) ? '' : request()->post('category_img'),
            'classJumpUrl' => is_null(request()->post('category_jump')) ? '' : request()->post('category_jump'),

        ]);
        OperateLogLogic::add(Admin::user()->user_id);
        return success();
    }

    public function productSpecsList(IdRequest $request): JsonResponse
    {
        $specs = ShopProductSpecsLogic::getByWhere(['productId' => $request->post('product_id'), 'psIsDelete' => 2]);
        return success($specs);
    }

    /**
     * action
     * @param ActionRequest $request
     * @return JsonResponse
     */
    public function action(ActionRequest $request): JsonResponse
    {
        $table = ucfirst(lineToHump($request->table));
        $class = implode('\\', ['\App', 'Admin', 'Actions', $table, $table . ucfirst($request->name) . 'Action']);
        $class = new $class;
        $modelClass = implode('\\', ['\App', 'Models', $table . 'Model']);
        $toaStr = $class->handle($modelClass::detail($request->primaryKey), $request)->getPlugin();
        if ($toaStr->getOptions()['toastr']['type'] === 'success') return success();
        else return fail();
    }

    /**
     * batch
     * @param BatchRequest $request
     * @return JsonResponse
     */
    public function batch(BatchRequest $request): JsonResponse
    {
        $table = ucfirst(lineToHump($request->table));
        $class = implode('\\', ['\App', 'Admin', 'Actions', 'Batch', 'Batch' . $table . ucfirst($request->name)]);
        $class = new $class;
        $modelClass = implode('\\', ['\App', 'Models', $table . 'Model']);
        $modelClass = new $modelClass;
        $collection = $modelClass->newQuery()->whereIn($modelClass->getKeyName(), $request->ids)->get();
        $toaStr = $class->handle($collection)->getPlugin();
        if ($toaStr->getOptions()['swal']['type'] === 'success') return success();
        else return fail();
    }
}
